﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using RTW.Core.Controllers;
using RTW.Model;
using RTW.Servers;

namespace RTW.Web.Areas.Unit.Controllers
{
    [Area("Unit")]
    public class HomeController : BaseController
    {
        public UnitServers unitservers;

        public HomeController()
        {
            unitservers = new UnitServers();
        }
        // GET: Index
        public IActionResult Index()
        {
            return View();
        }
        public async Task<IActionResult> IndexFrom(int? id)
        {
            //绑定父级机构列表
            ViewBag.ulist = new MultiSelectList(await unitservers.GetAll(), "DWID", "DWMC");
            var model = await unitservers.GetById(id);
            return View(model);
        }
        [HttpPost]
        public async Task<IActionResult> IndexFrom(SysUnit m)
        {

            //绑定父级机构列表
            ViewBag.ulist = new MultiSelectList(await unitservers.GetAll(), "DWID", "DWMC");
            if (m != null)
            {

                if (m.DWID == 0)
                {
                    bool flag =  await unitservers.AnyByName(m.DWMC);
                    if (flag)
                    {
                        return Json(Failed("用户名已存在！"));
                    }
                    flag = await unitservers.AnyByCode(m.DWDM);
                    if (flag)
                    {
                        return Json(Failed("编码已存在！"));
                    }
                    int b =await unitservers.Add(m);

                    return Json(MsgResult(b == 1));
                }
                else
                {
                    bool flag = await unitservers.AnyByName(m.DWMC);
                    if (flag)
                    {
                        return Json(Failed("用户名已存在！"));
                    }
                    flag = await unitservers.AnyByCode(m.DWDM);
                    if (flag)
                    {
                        return Json(Failed("编码已存在！"));
                    }

                    int b=await unitservers.Edit(m);
                    return Json(MsgResult(b == 1));
                }
            }
            return View(m);

        }
        [HttpPost]
        public async Task<IActionResult> del(string ids)
        {
          var res=  await unitservers.Del(ids);
            return Json(res>1);
        }



        public async Task<IActionResult> GetAllUnitJson() {
           //var dd=Json(await unitservers.GetUnit());
           // return dd;
            var res = await unitservers.GetAll();
            return Json(ListResult<SysUnit>(res));
        }


        public async Task<IActionResult> GetZTreeUnitJson() {
            var res = await unitservers.GetAll();
            return Json(res);
        }



    }
}